package xyz.quanguanjia.masterboy;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.HashMap;
import java.util.regex.Pattern;

import xyz.quanguanjia.masterboy.decoration.HomeItemDecoration;
import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;

public class MBDLoginActivity extends AppCompatActivity implements HomeItemDecoration.HomeItemClickListener {
    private Button confirmButton;
    private Button smsButton;
    private EditText phoneTextEdit;
    private EditText smsTextEdit;

    private CountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        confirmButton = findViewById(R.id.edit_confirm_button);
        phoneTextEdit = findViewById(R.id.edit_login_phone);
        smsTextEdit = findViewById(R.id.edit_login_code);
        smsButton = findViewById(R.id.login_sms_button);

        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(MBDLoginActivity.this.phoneTextEdit.getText().toString())) {
                    Toast.makeText(MBDLoginActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (false == MBDLoginActivity.validatedPhone(MBDLoginActivity.this.phoneTextEdit.getText().toString())) {
                    Toast.makeText(MBDLoginActivity.this, "手机号码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                String phoneText = phoneTextEdit.getText().toString();
                String smsText = smsTextEdit.getText().toString();
                MBDLoginActivity.this.doLoginRequest(phoneText,smsText,new MBDLoginActivity.CallBack() {
                    @Override
                    public void loginCompletion(Error error,String token) {
                        if (error == null) {
                            Toast.makeText(MBDLoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                            //设置 token
                            MBDUserCenter.shared().setToken(token);
                            MBDAccountInfoModel.fetch();

                            //退出当前页面
                            MBDLoginActivity.this.finish();
                        } else {
                            MBDUserCenter.shared().setToken("");

                            //居中
                            Toast toast = Toast.makeText(MBDLoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();


                        }


                    }
                });

            }
        });

        smsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(MBDLoginActivity.this.phoneTextEdit.getText().toString())) {
                    Toast.makeText(MBDLoginActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (false == MBDLoginActivity.validatedPhone(MBDLoginActivity.this.phoneTextEdit.getText().toString())) {
                    Toast.makeText(MBDLoginActivity.this, "手机号码不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                MBDLoginActivity.this.smsButton.setEnabled(false);

                MBDLoginActivity.this.smsButton.setBackgroundResource(R.drawable.button_disabled_background);

                MBDLoginActivity.this.timer = new CountDownTimer(60000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        // 每秒钟执行的操作（可选）
                        long secondsRemaining = millisUntilFinished / 1000;
                        // 可以更新 UI，显示剩余时间
                        Log.d("Timer", "剩余时间: " + secondsRemaining + " 秒");
                        MBDLoginActivity.this.smsButton.setText(secondsRemaining + " S");
                    }

                    public void onFinish() {
                        // 计时结束后执行的操作，即执行方法 A
                        MBDLoginActivity.this.smsButton.setEnabled(true);
                        MBDLoginActivity.this.smsButton.setText("获取验证码");
                        MBDLoginActivity.this.smsButton.setBackgroundResource(R.drawable.button_enable_background);


                    }
                }.start();

                MBDLoginActivity.this.doSMSRequest(phoneTextEdit.getText().toString(),new MBDLoginActivity.CallBack() {
                    @Override
                    public void smsCompletion(boolean success) {
                        Toast.makeText(MBDLoginActivity.this, "验证码获取成功！", Toast.LENGTH_SHORT).show();
                    }


                });
            }
        });
        // 设置退出动画
    }


    public static boolean validatedPhone(String phoneStr) {
        String phone = phoneStr.trim();
        String regex = "^1\\d{10}$";
        boolean result = Pattern.matches(regex, phone);
        return result;
    }

    private void doSMSRequest(String phoneNumber ,MBDLoginActivity.CallBack callBack) {
        if (TextUtils.isEmpty(phoneNumber)) {
            return;
        }

        MBDHttpClient client = MBDHttpClient.shared();

        HashMap<String,String > params = new HashMap<String,String>();
        params.put("phoneNumber",phoneNumber);

        client.doRequest(ServiceType.SERVICE_VERIFICATIONCODE,params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    callBack.smsCompletion(response.success());
                } else {
                    callBack.smsCompletion(false);
                }
            }
        });

    }

    private void doLoginRequest(String phoneNumber ,String smsCode,MBDLoginActivity.CallBack callBack) {
        assert !TextUtils.isEmpty(phoneNumber);
        assert !TextUtils.isEmpty(smsCode);

        HashMap<String,String > params = new HashMap<String,String>();
        params.put("phoneNumber",phoneNumber);
        params.put("verificationCode",smsCode);

        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_LOGIN,params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    if (response.data instanceof String) {
                        System.out.println("网络请求返回结果" + response.data);
                        callBack.loginCompletion(null,(String) response.data);
                    } else {
                        callBack.loginCompletion(error,"");
                    }
                } else {
                    callBack.loginCompletion(error,"");
                }
            }
        });
    }

    public interface CallBack {
         default public void smsCompletion(boolean success) {

         }
        default public void loginCompletion(Error error,String token){

        }
    }


    @Override
    public void finish() {
        super.finish();
        if (null != this.timer) {
            this.timer.cancel();
        }
        overridePendingTransition(0, R.anim.activity_top_to_bottom_exit);
    }

    @Override
    public void onItemClick(int position) {
//        Intent intent = new Intent(MBDSettingActivity.this, MBDAboutActivity.class);
//        startActivity(intent);
    }
}